package im.composer.vapu.adapter.op;

import im.composer.audio.engine.Source;
import im.composer.vapu.VAPU;
import jass.engine.BufferNotAvailableException;
import jass.engine.SinkIsFullException;

import org.jaudiolibs.audioops.AudioOp;
import org.jaudiolibs.audioservers.AudioConfiguration;

public class OpAdapter extends VAPU {

	private final AudioOp op;

	public OpAdapter(AudioOp op) {
		if(op==null){
			throw new IllegalArgumentException();
		}
		this.op = op;
	}

	@Override
	public synchronized void configure(AudioConfiguration context) throws Exception {
		super.configure(context);
		op.initialize(context.getSampleRate(), context.getMaxBufferSize());
	}

	@Override
	public synchronized Object addSource(Source s, boolean p) throws SinkIsFullException {
		if(!getSources().isEmpty()){
			throw new SinkIsFullException();
		}
		return super.addSource(s, p);
	}

	@Override
	protected void executeCommand(long timeStamp, String command) {

	}

	@Override
	protected void computeBuffer() {
		if(getSources().isEmpty()){
			return;
		}
		try {
			float[][] inputs = getSources().get(0).getBuffer().getAllChannels();
			float[][] outputs = buf.getAllChannels();
			op.processReplace(bufferSize, outputs, inputs);
		} catch (BufferNotAvailableException e) {
		}
	}

}
